package com.wangy.controller;

import com.wangy.bean.Permission;
import com.wangy.bean.Role;
import com.wangy.bean.RolePermission;
import com.wangy.service.RolePermissionService;
import com.wangy.service.RoleService;
import com.wangy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * *@Author yyzb
 * *@Date 2024/10/27 14:46
 * *@Version 1.0
 */

@RestController
@RequestMapping("admin/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    RolePermissionService rolePermissionService;

    //    1. 获取所有角色
    @GetMapping("getAllRoles")
    public Result<List<Role>> getAllRoles() {
        return Result.of(200, "success", roleService.getAllRoles());

    }

    //    2. 根据角色ID删除角色
    @DeleteMapping("deleteRole/{roleId}")
    public Result<Void> deleteRoleById(@PathVariable Long roleId) {
        roleService.deleteRole(roleId);
        return Result.of(200, "success", null);

    }

    //    3. 添加新角色
    @PostMapping("addRole")
    public Result<Void> addRole(@RequestParam String roleName) {
        roleService.addRole(roleName);
        return Result.of(200, "success", null);

    }

    //    4. 根据角色ID获取菜单
    @GetMapping("permissions/{roleId}")
    public Result<List<Permission>> getPermissionsByRoleId(@PathVariable Long roleId) {
        List<Permission> permissionsByRoleId = rolePermissionService.getPermissionsByRoleId(roleId);
        return Result.of(200, "success", permissionsByRoleId);

    }

    //    5. 为角色分配权限
    @PostMapping("assignPermissionsToRole")
    public Result<Void> assignPermissionsToRole(@RequestBody RolePermission rolePermission) {
        rolePermissionService.addRolePermissions(rolePermission.getRoleId(),
                Arrays.stream(rolePermission.getPermissionIds().split(",")).map(Long::parseLong).collect(Collectors.toList()));
        return Result.of(200, "success", null);
    }
}
